package com.dlwx.parttimetalent.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.OrderRecExpandAdapter;
import com.dlwx.parttimetalent.bean.BaseBean;
import com.dlwx.parttimetalent.bean.OrderRecBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.CheckChangeInter;
import com.dlwx.parttimetalent.ui.DaRenActivity;
import com.dlwx.parttimetalent.ui.EditLabelActivity;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.views.MyProgressLoading;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

public class TwoFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    Unbinder unbinder;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.expand_listview)
    ExpandableListView expandListview;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.sw_all)
    Switch swAll;
    @BindView(R.id.image_header)
    CircleImageView imageHeader;
    @BindView(R.id.tv_nickName)
    TextView tvNickName;

    private OrderRecExpandAdapter mAdapter;
    private List<OrderRecBean.BodyBean> groupList = new ArrayList<>();
    private MyProgressLoading loadingDialog;

    private Intent jumpIntent;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public TwoFragment() {
    }

    public static TwoFragment newInstance(String param1, String param2) {
        TwoFragment fragment = new TwoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadingDialog = new MyProgressLoading(getActivity(), R.style.DialogStyle);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_two, container, false);
        unbinder = ButterKnife.bind(this, view);
        jumpIntent = new Intent();
        initView();
        return view;
    }
    @Override
    public void onResume() {
        super.onResume();
        String nickName = (String) SPUtils.get(getActivity(), Constant.NICK_NAME, "");
        String headUrl = (String) SPUtils.get(getActivity(), Constant.HEAD_URL, "");
        tvNickName.setText(nickName);
        Glide.with(getActivity()).load(headUrl).into(imageHeader);
        getDatas();
    }

    private void getDatas() {
        loadingDialog.show();
        OkgoUtil.get(Http.MyIntentList, getActivity())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        OrderRecBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<OrderRecBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if (parentBean.getCode() == Constant.SUCESS) {
                            jumpIntent.putExtra("bean", parentBean);
                            if(TwoFragment.this.isAdded()){
                                setDatas(parentBean.getBody());
                            }
                        } else {
                            ToastUtils.toastForShort(getActivity(), parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

    private void setDatas(List<OrderRecBean.BodyBean> body) {
        int allState = body.get(body.size() - 1).getAllStatus();
        swAll.setOnCheckedChangeListener(null);
        if (allState == 1) {
            swAll.setChecked(true);
        } else {
            swAll.setChecked(false);
        }
        groupList.clear();
        groupList.addAll(body);
        mAdapter.notifyDataSetChanged();
        int groupCount=expandListview.getCount();
        if(groupCount>0){
            for (int i = 0; i < groupCount; i++) {
                expandListview.expandGroup(i);
            }
        }
        swAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int state = 0;

                if (isChecked) {
                    state = 1;
                } else {
                    state = 2;
                }
                updateStatus("all", state, "");
            }
        });
    }

    private void initView() {
        tvMiddleTitle.setText("接单");
        tvMiddleTitle.setVisibility(View.VISIBLE);
        mAdapter = new OrderRecExpandAdapter(groupList, getActivity(), new CheckChangeInter() {
            @Override
            public void groupChange(int position, boolean status) {
                int state = 0;
                if (status) {
                    state = 1;
                } else {
                    state = 2;
                }
                updateStatus("2", state, position + "");
            }

            @Override
            public void childChange(int groupPosition, int childPosition, boolean status) {
                int state = 0;
                if (status) {
                    state = 1;
                } else {
                    state = 2;
                }
                updateStatus("1", state, groupPosition + "");
            }
        });

        expandListview.setGroupIndicator(null);
        expandListview.setAdapter(mAdapter);
        int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        expandListview.setIndicatorBounds(width - 100, width - 10);

    }

    private void updateStatus(String uptype, int status, String id) {
        loadingDialog.show();
        OkgoUtil.post(Http.UpdateLabelState, getActivity())
                .params("uptype", uptype)
                .params("state", status)
                .params("labelid", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        BaseBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<BaseBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if (parentBean.getCode() == Constant.SUCESS) {

                        } else {
                        }
                        getDatas();
                        ToastUtils.toastForShort(getActivity(), parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.rl_title, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_title:
                startActivity(new Intent(getActivity(), DaRenActivity.class));
                break;
            case R.id.tv_confirm:
                jumpIntent.setClass(getActivity(), EditLabelActivity.class);
                startActivity(jumpIntent);
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
